package net.cyl.controller;

import com.google.code.kaptcha.Producer;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import net.cyl.controller.request.SendCodeRequest;
import net.cyl.emums.SendCodeEnum;
import net.cyl.service.NotifyService;
import net.cyl.util.CommonUtil;
import net.cyl.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/account/v1/notify")
@Slf4j
public class NotifyController {
    // 注入Producer
    @Autowired
    private Producer captchaProducer;
    // 注入NotifyService
    @Autowired
    private NotifyService notifyService;
    // 注入RedisTemplate
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    // 验证码过期时间
    private static final long  EXPIRE_TIME = 60 * 1000 * 10;
    // 获取验证码
    @GetMapping("/captcha")
    public void sendCaptcha(HttpServletRequest request, HttpServletResponse response) {
        // 生成验证码
        String captcha = captchaProducer.createText();

        log.info("captcha:{}", captcha);
        // 将验证码存入Redis
        redisTemplate.opsForValue().set(getCaptchaKey(request), captcha, EXPIRE_TIME, TimeUnit.MILLISECONDS);
        // 生成验证码图片
        BufferedImage image = captchaProducer.createImage(captcha);
        try {
            // 将图片输出到浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            log.error("send captcha error{}", e.getMessage());
        }

    }


private String getCaptchaKey(HttpServletRequest request) {
        // 获取用户IP
        String ip = CommonUtil.getIpAddr(request);
        // 获取用户浏览器信息
        String userAgent = request.getHeader("User-Agent");

        // 生成验证码key
        String key="account-service:captcha:" +CommonUtil.MD5(ip + userAgent);
        log.info("captcha key:{}", key);
        return key;
}


    // 发送短信
    @PostMapping("/sms")
    public JsonData sendSms(@RequestBody SendCodeRequest sendCodeRequest, HttpServletRequest request) {
        // 获取验证码key
        String key = getCaptchaKey(request);
        // 从Redis中获取验证码
        String cacheCaptcha = (String) redisTemplate.opsForValue().get(key);
        // 获取用户输入的验证码
        String captcha = sendCodeRequest.getCaptcha();
        // 判断验证码是否正确
        if (captcha != null && captcha.equalsIgnoreCase(cacheCaptcha)) {
            // 删除Redis中的验证码
            redisTemplate.delete(key);
            // 发送短信
            return notifyService.sendSms(SendCodeEnum.USER_REGISTER, sendCodeRequest.getTo());
        }
        else {
            // 验证码错误
            return JsonData.buildError("验证码错误");
        }

    }
}